package com.cjx.sec.web.filter;

import com.cjx.sec.pojo.doo.AuditLog;
import com.cjx.sec.repository.AuditLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 基于Filter的审计过滤器
 * @author cjx
 * @date 2024/8/25 0:08
 */
@Slf4j
@Order(3)
@Component
@SuppressWarnings("ALL")
public class AuditLogFilter extends OncePerRequestFilter {
    @Resource
    private AuditLogRepository auditLogRepository;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("*********3、审计*********");
        
        AuditLog auditLog = new AuditLog();
        auditLog.setHttpMethod(request.getMethod());
        auditLog.setPath(request.getRequestURI());
        //放入持久化上下文中，供异常处理使用
        auditLogRepository.save(auditLog);
        request.setAttribute("auditLogId", auditLog.getId());
        
        // 执行请求
        filterChain.doFilter(request, response);
        
        // 执行完成，从持久化上下文中获取，并记录响应信息
        auditLog = auditLogRepository.findById(auditLog.getId()).get();
        auditLog.setHttpStatus(response.getStatus());
        
        auditLogRepository.save(auditLog);
    }
}
